import * as vscode from 'vscode';
// let TurndownService = require('turndown');
import TurndownService from 'turndown';
export let outputChannel = vscode.window.createOutputChannel('Comment Translate'); //用于创建一个新的输出通道。输出通道通常用于在 VS Code 的输出面板中显示日志或调试信息。
let service = new TurndownService();
function getCurrentActiveFocusViewText(): string {
	const activeEditor = vscode.window.activeTextEditor;

	if (activeEditor) {
		// 获取当前编辑器中的文档
		const document = activeEditor.document;

		// 获取文档的所有文本内容
		const content = document.getText();

		// 显示文件内容（可以根据需要处理）
		// vscode.window.showInformationMessage('File content retrieved.', content);

		// 打印内容到输出面板（调试用）
		console.log(content);
		return content;
	} else {
		vscode.window.showErrorMessage('No active editor found.');
		return '';
	}
}

import { translateHtml } from './translateService/htmlparserTranslate';
// This method is called when your extension is deactivated
export function deactivate() {}
function replaceCurrentActiveFocusViewText(replaceText: string) {
	// vscode.window.showInformationMessage(' 准备替换的文本', replaceText);

	let editor = vscode.window.activeTextEditor;
	if (editor) {
		let textContent = editor.document.getText();
		if (replaceText) {
			editor.edit((editBuilder) => {
				editBuilder.replace(
					new vscode.Range(
						0,
						0,
						editor.document.lineCount,
						editor.document.lineAt(editor.document.lineCount - 1).range.end.character,
					),
					replaceText,
				);
				//for test
				// require('fs').writeFileSync('A:/Github_Learning_Project/translated.md', replaceText);
			});
		}
		// vscode.window.showInformationMessage('最终文本', editor.document.getText());
	}
}
function convertMarkdownToHtml(markdown: string): string {
	{
		let marked = require('marked');
		let html = marked.marked(markdown);
		// vscode.window.showInformationMessage('Converting markdown to html success.', html);

		return html;
	}
}

function convertHtmlToMarkdown(html: any) {
	try {
		service.addRule('preserveCodeBlocks', {
			filter: function (node: any) {
				// 过滤 <pre><code> 块
				return node.nodeName === 'PRE' && node.firstChild && node.firstChild.nodeName === 'CODE';
			},
			replacement: function (content: any, node: any) {
				// 获取代码块的内容并用 ``` 包裹
				const codeContent = node.firstChild.textContent;
				const language = node.firstChild.getAttribute('class')?.replace('language-', '') || '';
				// return ' ```${language}\n${codeContent}\n```\n';
				return '\n' + `\`\`\`${language}\n${codeContent}\n\`\`\`` + '\n';
			},
		});
		let md = service.turndown(html);
		// vscode.window.showInformationMessage('Converting html to markdown Markdown成功.', md);
		return md;
	} catch (error: any) {
		vscode.window.showInformationMessage('Converting html to markdown error.', error.message);
		console.log(error);
		return '';
	}
}
function getEXtractCodeBlock(text: string) {
	const codeBlocks = extractCodeBlocks(text);
	console.log(codeBlocks);
	codeBlocks.forEach((element) => {
		element = '\n' + element + '\n';
		console.log(element);
	});
	return codeBlocks;
}

function extractCodeBlocks(text: String) {
	// 正则表达式匹配 Markdown 格式的代码块
	const codeBlockRegex = /```[\s\S]*?```/g;

	// 匹配到的代码块数组
	const matches = text.match(codeBlockRegex);

	// 如果没有匹配到代码块，返回空数组
	if (!matches) return [];

	// 处理每个匹配到的代码块，去掉 ```` ``` ```` 包裹的部分
	return matches.map((block) => {
		return block;
	});
}

import { cheerioExtractor } from './translateService/cheerioTranslate';
export function activate(context: vscode.ExtensionContext) {
	console.log('Congratulations, your extension "readme_translate" is now active!');
	let replaceCommand = vscode.commands.registerCommand('readme_translate.translateAndReplace', async () => {
		let originMarkdown = getCurrentActiveFocusViewText();
		let html = convertMarkdownToHtml(originMarkdown);
		let htmlTranslated = await cheerioExtractor(html);
		vscode.window.showInformationMessage('翻译成功', htmlTranslated);
		let markdownTranslated = convertHtmlToMarkdown(htmlTranslated);
		let resultMarkdown;
		let result = replaceCurrentActiveFocusViewText(markdownTranslated);
	});

	const disposable = vscode.commands.registerCommand('readme_translate.helloWorld', () => {
		vscode.window.showInformationMessage('Hello   super  from readme_translate!');
	});
	context.subscriptions.push(disposable, replaceCommand);
}
